package com.sa.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sa.bean.entity.UserDO;
import com.sa.bean.entity.UserFeatureDO;
import com.sa.bean.vo.UserVO;
import com.sa.mapper.UserMapper;
import com.sa.service.UserFeatureService;
import com.sa.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {

    private final UserFeatureService userFeatureService;
    private final UserMapper userMapper;

    @Override
    public UserVO selectById(Long userId) {
        // 查询用户信息
        UserDO existEntity = getById(userId);
        if(existEntity == null){
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(existEntity,userVO);
        // 查询用户特征列表
        List<UserFeatureDO> features = userFeatureService.selectById(userId);
        if(CollUtil.isEmpty(features)){
            return userVO;
        }
        // 设置特征值列表
        List<String> featureValue = features.stream().map(UserFeatureDO::getFeatureValue)
                .collect(Collectors.toList());
        userVO.setFeatures(featureValue);
        return userVO;
    }

    @Override
    public Integer selectCount() {
        Integer count = userMapper.selectCountForUser();
        return count;
    }

    @Override
    public String selectNameById(Long id) {
        return userMapper.selectNameById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(String username, String phone, List<String> features) {
        UserDO userDO = new UserDO();
        userDO.setUsername(username);
        userDO.setPhone(phone);
        save(userDO);
        // 保存特征
        List<UserFeatureDO> featureList = features.stream().map(feature -> {
            UserFeatureDO userFeatureDO = new UserFeatureDO();
            userFeatureDO.setUserId(userDO.getId());
            userFeatureDO.setFeatureValue(feature);
            return userFeatureDO;
        }).collect(Collectors.toList());
        userFeatureService.saveBatch(featureList);
    }

    public int getNumber(){
        System.out.println("getNumber");
        return 1;
    }
}
